package com.lc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.mapper.MenuMapper;
import com.lc.pojo.Admin;
import com.lc.pojo.Menu;
import com.lc.service.IMenuService;
import com.lc.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 龙晨
 * @since 2021-11-17
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Menu> getMenuByAdminId() {
        //从全局对象中获取已登录的用户id
        Integer id = AdminUtils.getCurrentAdmin().getId();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        //从redis中获取菜单数据
        List<Menu> menus = (List<Menu>) operations.get("menu_" + id);
        //如果为空，则通过数据库查询
        if (CollectionUtils.isEmpty(menus)){
            menus =menuMapper.getMenusByAdminId(id);
            //将所得值存入redis中
            operations.set("menu_"+id,menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
